import store from '@/store'

export async function checkSession() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success() {
        return resolve(true)
      },
      fail() {
        return resolve(false)
      }
    })
  })
}

export async function bindSeller() {
  // const token = this.$store.state.token
  // const referrer = this.$store.state.referrer
  // if (!token) {
  //   return
  // } 
  // if (!referrer) {
  //   return 
  // }
}

// 检测登录状态，返回 true / false
export async function checkHasLogined() {
  const token = store.state.token
  if (!token) {
    return false
  }
  const loggined = await checkSession()
  if (!loggined) {
    store.commit('$uStore', {
      name: 'token',
      value: ''
    })
    return false
  }
  // 调用接口检查token 是否过期
  // const checkTokenRes = await 

  return true
}

export async function wxaCode() {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        return resolve(res.code)
      },
      fail() {
        wx.showToast({
          title: '获取code失败',
          icon: 'none'
        })
        return resolve('获取code失败')

      }
    })
  })
}

export async function login(page) {
  const that = this
  wx.login({
    success(res) {
      const extConfigSync = wx.getExtConfigSync()
      if (extConfigSync.subDomain) {
        // 调用微信服务器登录接口
      }
    }
  })
}

export function loginOut() {
  store.commit('$uStore', {
    name: 'token',
    value: ''
  })
  store.commit('$uStore', {
    name: 'uid',
    value: ''
  })
}

export async function checkAndAuthorize(scope) {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success(res) {
				if (!res.authSetting[scope]) {
					uni.authorize({
						scope: scope,
						success() {
							resolve() // 无返回参数
						},
						fail(e) {
							console.error(e)
							uni.showModal({
								title: '无权操作',
								content: '需要获得您的授权',
								showCancel: false,
								confirmText: '立即授权',
								confirmColor: '#e64340',
								success(res) {
									uni.openSetting();
								},
								fail(e) {
									console.error(e)
									reject(e)
								},
							})
						}
					})
				} else {
					resolve() // 无返回参数
				}
			},
			fail(e) {
				console.error(e)
				reject(e)
			}
		})
	})
}